<template>
  <div :class="$style.root">
    <div @click="print" :class="$style.btn">打印</div>
  </div>
</template>

<script>
import Vue from "vue";
import html2canvas from 'html2canvas';
import htmlToPdf from "./utils/htmlToPdf";
import Print from './utils/print'
Vue.use(Print)
Vue.use(htmlToPdf);
export default {
  name: "lcap-stt-print",
  props: {
    downloadFileType: {
      type: String,
      default: "pdf", // pdf png
    },
    title: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      el: "",
    };
  },
  methods: {
    init() {
      let el = document.querySelector('div[type=root]')
      if(!el) {
        el = document.querySelector('body div')
      }
      if(el) {
        this.el = el;
        el.id = 'printArea'
        el.ref = 'printArea'
      }
    },
    print() {
      this.$print(this.el)
      if(this.downloadFileType) {
        if(this.downloadFileType==='pdf') {
          this.pdf()
        }
        if(this.downloadFileType==='png') {
          this.png()
        }
      }
    },
    pdf () {
      window.scrollTo(0, 0);
      this.getPdf(this.title||document.title);
    },
    png () {
      html2canvas(this.el, {
        backgroundColor: '#ffffff'
      }).then(canvas => {
        var imgData = canvas.toDataURL("image/jpeg");
        this.fileDownload(imgData);
      })
    },
    fileDownload (downloadUrl, file) {
      let aLink = document.createElement("a");
      aLink.style.display = "none";
      aLink.href = downloadUrl;
      aLink.download = file;
      // 触发点击-然后移除
      document.body.appendChild(aLink);
      aLink.click();
      document.body.removeChild(aLink);
    },
  },
  mounted() {
    this.init()
  }
};
</script>

<style module>
.root {
}
.btn {
  width: 60px;
  text-align: center;
  background-color: #5781fc;
  color: #fff;
  border-radius: 5px;
  outline: none;
  cursor: pointer;
  padding: 5px 12px;
  border: none;
}
</style>
